package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"net/http"
	"os"
	"path/filepath"
	"time"
)

func Upload(c *gin.Context) {
	now := time.Now()
	// 文件夹路径
	fileDir := fmt.Sprintf("static/upload/%s/%d/%d/%d", "img", now.Year(), now.Month(), now.Day())
	// 创建文件夹 ModePerm是0777
	os.MkdirAll(fileDir, os.ModePerm)
	// 获取文件
	file, _ := c.FormFile("editormd-image-file")
	filePathStr := filepath.Join(fileDir, file.Filename)
	// 将文件上传到指定路径
	err := c.SaveUploadedFile(file, filePathStr)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"success": 0,
			"message": "上传失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": 1,
		"message": "上传成功",
		"url":     viper.GetString("online.addr") + ":" + viper.GetString("http.port") + "/" + filePathStr,
	})

}
